package com.pangu.web.handler.admin.platform;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import com.pangu.web.handler.admin.utils.page.Pagination;
import com.pangu.web.model.*;
import com.pangu.web.service.GameRoomService;
import com.pangu.web.service.repository.jpa.PlayUserRepository;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.ModelAndView;

import com.pangu.core.BMDataContext;
import com.pangu.core.cache.CacheHelper;
import com.pangu.util.BeiMiDic;
import com.pangu.util.GameUtils;
import com.pangu.util.Menu;
import com.pangu.web.handler.Handler;
import com.pangu.web.service.repository.es.PlayUserESRepository;
import com.pangu.web.service.repository.jpa.GamePlaywayRepository;
import com.pangu.web.service.repository.jpa.GameRoomRepository;
/**
 * @author Chris
 * @date 2018/4/26 15:26
 * @todo   游戏房间信息
*/
@Controller
@RequestMapping("/apps/platform")
public class GameRoomController extends Handler{
	
	@Autowired
	private GameRoomRepository gameRoomRes ;
	
	@Autowired
	private PlayUserESRepository playUserRes;
	
	@Autowired
	private GamePlaywayRepository playwayRes;

	@Autowired
	private GameRoomService gameRoomService;

	@Autowired
	private PlayUserRepository playUserRepository;


		/**
		 * @author Chris
		 * @date 2018/5/9 16:08
		 * @todo   查询游戏房间列表
		*/
	@RequestMapping({"/roomList"})
	@RequiresPermissions("sys:room:select")
	public String playRecord(GameRoom gameRoom, String findContent, ModelMap modelMap, Integer pageNo, Integer pageSize, HttpServletRequest request) {
		modelMap.put("findContent", findContent);
		if (pageSize == null) {
			pageSize = 25;
		}
		//过去表单中输入的参数
		Pagination pagination = null;
		try {

			if (gameRoom != null) {
				if (com.pangu.web.handler.admin.utils.StringUtils.isBlank(gameRoom.getGame())) {
					gameRoom.setGame("3");
				}
			/*	HttpSession session = request.getSession();
				session.setAttribute("gameType", playRecord.getGameType());*/
			}
			pagination=gameRoomService.getGameRootByCache(gameRoom, pageNo, pageSize);
			List<GameRoom> gameRoomList = pagination.getList();
			List<String> playUsersList = new ArrayList<String>() ;
			for(GameRoom gr : gameRoomList){
				List<PlayUserClient> players = CacheHelper.getGamePlayerCacheBean().getCacheObject(gr.getId(),gr.getOrgi()) ;
				gr.setPlayers(players.size());
				if(!StringUtils.isBlank(gr.getMaster())){
					playUsersList.add(gr.getMaster()) ;
				}
				if(!StringUtils.isBlank(gr.getPlayway())){
					gr.setGamePlayway((GamePlayway) CacheHelper.getSystemCacheBean().getCacheObject(gr.getPlayway(), super.getOrgi(request)));
				}
			}
			if(playUsersList.size() > 0){
				for(GameRoom room : gameRoomList){
					for(String id : playUsersList ){
					   PlayUser playUser=playUserRepository.findById(id);
					   if(playUser!=null){
						   if(playUser.getId().equals(room.getMaster())){
							   room.setMasterUser(playUser); break ;
						   }
					   }
					   }
				}

			}
			modelMap.put("roomList", gameRoomList);
			modelMap.put("page", pagination.getPageHtml());
			modelMap.addAttribute("gameModelList", BeiMiDic.getInstance().getDic(BMDataContext.BEIMI_SYSTEM_GAME_TYPE_DIC)) ;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/platform/game/room/info";
	}


	@RequestMapping({"/gameroom"})
	@RequiresPermissions("sys:room:select")
	public ModelAndView gameusers(ModelMap map , HttpServletRequest request , @Valid String id){
		Page<GameRoom> gameRoomList = gameRoomRes.findByOrgi(super.getOrgi(request), new PageRequest(super.getP(request), super.getPs(request) , new Sort(Sort.Direction.DESC, "createtime"))) ;

		map.addAttribute("gameRoomList", gameRoomList) ;
		
		map.addAttribute("gameModelList", BeiMiDic.getInstance().getDic(BMDataContext.BEIMI_SYSTEM_GAME_TYPE_DIC)) ;
		
		return request(super.createAppsTempletResponse("/platform/game/room/index"));
	}
	

	@RequestMapping({"/gameroom/delete"})
	@RequiresPermissions("sys:room:delete")
	public ModelAndView delete(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String game){
		if(!StringUtils.isBlank(id)){
			GameRoom gameRoom = gameRoomRes.findByIdAndOrgi(id, super.getOrgi(request)) ;
			if(gameRoom!=null){
				gameRoomRes.delete(gameRoom);
			}
			CacheHelper.getExpireCache().remove(gameRoom.getId());
			GameUtils.removeGameRoom(gameRoom.getId(),gameRoom.getPlayway(), super.getOrgi(request));
			CacheHelper.getGameRoomCacheBean().delete(gameRoom.getId(), super.getOrgi(request)) ;
			CacheHelper.getBoardCacheBean().delete(gameRoom.getId(), super.getOrgi(request)) ;
			List<PlayUserClient> playerUsers = CacheHelper.getGamePlayerCacheBean().getCacheObject(id, super.getOrgi(request)) ;
			for(PlayUserClient tempPlayUser : playerUsers){
				CacheHelper.getRoomMappingCacheBean().delete(tempPlayUser.getId(), super.getOrgi(request)) ;
			}
			
			CacheHelper.getGamePlayerCacheBean().clean(gameRoom.getId() , gameRoom.getOrgi()) ;
		}
		return request(super.createRequestPageTempletResponse("redirect:/apps/platform/gameroom.html"));
	}

	/**
	 * @author Chris
	 * @date 2018/5/4 16:17
	 * @todo  查看房间详情
	*/
	@RequestMapping({"/roomInfo"})
	@RequiresPermissions("sys:room:select")
	@ResponseBody
	public Map<String,Object> queryInfoByRoomId(ModelMap map , @Valid String roomId, HttpServletRequest request){

		List<GameRoom> gameRoom=gameRoomRes.findByRoomidAndOrgi(roomId,getOrgi(request));

		//从缓存中查询房间的信息
	    //GameRoom gr = (GameRoom) CacheHelper.getGameRoomCacheBean().getCacheObject(roomId, BMDataContext.SYSTEM_ORGI) ;
		List<PlayUserClient> list=CacheHelper.getGamePlayerCacheBean().getCacheObject(roomId, BMDataContext.SYSTEM_ORGI);
        if(gameRoom.size()>0){
			resultMap.put("roomInfo",gameRoom.get(0));
		}
		resultMap.put("userList",list);


		return resultMap;
	}



}
